//
//  SQLiteManager.cpp
//  match2
//
//  Created by Tri Vo on 7/10/13.
//
//

#include "SQLiteManager.h"


SQLiteManager* SQLiteManager::mInstance = NULL;

SQLiteManager* SQLiteManager::getInstance() {
    if (mInstance == NULL) {
        mInstance = new SQLiteManager();
    }
    return mInstance;
}


bool SQLiteManager::openDB(char* fileName) {
    if (sqlite3_open(fileName, &mDatabase) == SQLITE_OK) {
        return true;
    }
    return false;
}

std::vector<std::vector<std::string> > SQLiteManager::query(char *query) {
    sqlite3_stmt *statement;
    std::vector<std::vector<std::string> > results;
    if (sqlite3_prepare_v2(mDatabase, query, -1, &statement, 0) == SQLITE_OK) {
        int cols = sqlite3_column_count(statement);
        int result = 0;
        while (true) {
            result = sqlite3_step(statement);
            if (result == SQLITE_ROW) {
                std::vector<std::string> values;
                for (int col = 0; col < cols; col++) {
                    values.push_back((char*)sqlite3_column_text(statement, col));
                }
            } else {
                break;
            }
        }
        sqlite3_finalize(statement);
    }
    
    std::string error = sqlite3_errmsg(mDatabase);
    if(error != "not an error") {
        CCLOG("Error: %s", &error);
    }
    return results;
    
}

void SQLiteManager::closeDB() {
    sqlite3_close(mDatabase);
}

SQLiteManager::~SQLiteManager() {
    mInstance = NULL;
}